package edu.xhu;

import java.util.ArrayList;

import com.bean.LibraryBookBean;
import com.constant.Constant;
import com.data.SearchLibraryData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.adapters.LibraryAdapter;
import edu.xhu.view.LoadingDialog;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 图书列表
 * @author swerit
 *
 */

public class BookListActivity extends Activity{

	private String keyWords;					//关键字
	private ListView bookList;
	private LibraryAdapter adapter;
	private TextView title;
	private Button btnBack;
	
	private ArrayList<LibraryBookBean> mLibraryData;
	private int mTotalCount;							//总共查找结果
	private int mLoadedCount = 0;						//已经加载到本地的总数
	private int mCurrentIndex = 1;						//当前page标签，最小值为2
	
	//标示跳转的来源界面
	public static final String FROM_SEARCH  = "search";
	public static final String FROM_ME		= "me";
	public static final String FROM			= "from";
	
	
	//控制listview加载更多按钮显示的控件
	private RelativeLayout buttonLoadNext;				//加载下一页数据的按钮
	private RelativeLayout loadingBar;					//正在加载中显示的进度条
	private View footer;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.books);
		
		initView();
		setListener();
		
		Intent intent = getIntent();
		String from = intent.getStringExtra(FROM);
		if (from.equals(FROM_SEARCH)){
//			title.setText("搜索结果");
			keyWords = intent.getStringExtra("key_words");
			
		}else if (from.equals(FROM_ME)){
			title.setText("我借的图书");
		}
		
		loadData();
	}
	
	private void initView(){
		bookList			= (ListView) findViewById(R.id.listview_books);
		title				= (TextView) findViewById(R.id.title);
		btnBack				= (Button) findViewById(R.id.button_back);
		
		//设置listview加载更多按钮
		footer			    = LayoutInflater.from(this).inflate(R.layout.listview_footer, null);
		bookList.addFooterView(footer);
		buttonLoadNext		= (RelativeLayout) footer.findViewById(R.id.button_load_next);
		loadingBar			= (RelativeLayout) footer.findViewById(R.id.progressbar_loading);
		
		//固定listview的高度，解决getview重复调用问题
		bookList.post(new Runnable() {
			public void run() {
				//获取通知栏的高度
				Rect rect = new Rect();
				View view = getWindow().findViewById(Window.ID_ANDROID_CONTENT);
				view.getWindowVisibleDisplayFrame(rect);
				int noticeBarHeight = rect.top;
				//获取屏幕的高度
				DisplayMetrics metric = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(metric);
				int screenHeight = metric.heightPixels; 				// 屏幕高度（像素）
				final int height_list = screenHeight- dip2px(BookListActivity.this, 45) - noticeBarHeight;
				LayoutParams params = bookList.getLayoutParams();
				params.height = height_list;
				bookList.setLayoutParams(params);
			}
		});
	}
	
	/**
	 * 加载第一页的数据
	 */
	private void loadData(){
		title.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(BookListActivity.this);
			}
		});
		
		
		RequestParameter parameter = new RequestParameter();
		parameter.add("title", keyWords);
		
		LoadData.loadData(Constant.SEARCH_LIBRARY_DATA, parameter, new RequestListener() {
			public void onComplete(Object obj) {
				SearchLibraryData data = (SearchLibraryData) obj;
				mLibraryData = data.getLibrary();
				if (mLibraryData == null){
					LoadingDialog.dismiss();
					Toast.makeText(BookListActivity.this, "没有找到", 0).show();
					return;
				}
				mTotalCount = data.getTotal();
				title.setText("找到" + data.getTotal() + "本");
				adapter = new LibraryAdapter(BookListActivity.this, mLibraryData);
				bookList.setAdapter(adapter);
				mLoadedCount += mLibraryData.size();
				
				LoadingDialog.dismiss();
			}
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(BookListActivity.this, ed);
			}
		});
	}
	
	/**
	 * 加载下一页的数据
	 */
	private void loadNextPageData(){
		title.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(BookListActivity.this);
			}
		});
		
		RequestParameter parameter = new RequestParameter();
		parameter.add("title", keyWords);
		parameter.add("count", mTotalCount + "");
		++mCurrentIndex;
		parameter.add("page", mCurrentIndex + "");
		
		LoadData.loadData(Constant.SEARCH_LIBRARY_DATA, parameter, new RequestListener() {
			public void onComplete(Object obj) {
				SearchLibraryData data = (SearchLibraryData) obj;
				ArrayList<LibraryBookBean> tmpBeans = data.getLibrary();
				adapter.addItems(tmpBeans);
				mLoadedCount += tmpBeans.size();
				
				loadEnd();
			}
			public void onError(ClientError ed) {
				mCurrentIndex--;
				loadEnd();
				LoadingDialog.dismiss();
				ErrorShow.showError(BookListActivity.this, ed);
			}
				
		});
	}
	
	/**
	 * 为控件设置点击事件
	 */
	private void setListener(){
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		
		bookList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(BookListActivity.this, WebviewActivity.class);
				intent.putExtra(WebviewActivity.REQUEST_URL, mLibraryData.get(position).url);
				intent.putExtra(WebviewActivity.REFERER, mLibraryData.get(position).referer);
				startActivity(intent);
			}
		});
		
//		buttonLoadNext.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				if (mLoadedCount >= mTotalCount){
//					Toast.makeText(BookListActivity.this, "已经加载所有数据", 0).show();
//					return;
//				}
//				if (loadingBar.getVisibility() == View.VISIBLE){
//					//正在加载则不处理
//					return;
//				}
//				
//				loadingBar.setVisibility(View.VISIBLE);
//				buttonLoadNext.setVisibility(View.GONE);
//				
//				loadNextPageData();
//			}
//		});
//		//加上这句，让footer不会响应点击事件
//		loadingBar.setOnClickListener(null);
		
		footer.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (mLoadedCount >= mTotalCount){
					Toast.makeText(BookListActivity.this, "已经加载所有数据", 0).show();
					return;
				}
				if (loadingBar.getVisibility() == View.VISIBLE){
					//正在加载则不处理
					return;
				}
				loadingBar.setVisibility(View.VISIBLE);
				buttonLoadNext.setVisibility(View.GONE);
				
				loadNextPageData();
			}
		});
	}
	
	private void loadEnd(){
		loadingBar.setVisibility(View.GONE);
		buttonLoadNext.setVisibility(View.VISIBLE);
		LoadingDialog.dismiss();
	}
	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			if (LoadingDialog.isShowing())
				LoadingDialog.dismiss();
			else {
				finish();
			}
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
}
